package com.hhq.demo.dao.impl;

import com.hhq.demo.dao.AdminDao;
import com.hhq.demo.utils.DateFormatUtil;
import com.hhq.demo.utils.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @author HHQ
 * @date 2021年12月14日
 */
public class AdminDaoImpl implements AdminDao {

    private String UPDATE_LOGIN_TIME = "update `users` set logintime=?,loginip=? where username=?";
    private String LOGIN = "select id from `users` where username=? and password=?";

    /**
     * 更新管理员登录的时间
     *
     * @param username  帐号
     * @param loginTime 登录时间，为当前时间
     * @param loginIp   登录的IP
     */
    @Override
    public void updateLoginTime(String username, Date loginTime, String loginIp) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(UPDATE_LOGIN_TIME);
            preparedStatement.setObject(1, DateFormatUtil.format(loginTime));
            preparedStatement.setObject(2, loginIp);
            preparedStatement.setObject(3, username);
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtil.close(connection,preparedStatement,null);
        }
    }

    /**
     * 管理员登录
     *
     * @param username 帐号
     * @param password 密码
     * @return 登录结果
     */
    @Override
    public boolean login(String username, String password) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(LOGIN);
            preparedStatement.setObject(1,username);
            preparedStatement.setObject(2,password);
            resultSet = preparedStatement.executeQuery();
            return resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtil.close(connection,preparedStatement,resultSet);
        }
        return false;
    }
}
